import * as utils from '../utils'

export const initFormConfig = (formItem: any) => {
  return {
    title: formItem.formTypeName,
    tips: '', // 提示语
    required: false, // 是否必填
    key: formItem.id, // 表单项key值

    columns: [], // 参数数据
    exportFn: '', // 计算公式
    isEdit: false // 是否可编辑
  }
}

// 初始化数据源配置
export const initInputConfig = (key: string) => {
  return {
    key,
    id: '' // 表单项ID
  }
}

// 输出计算结果
export const exportValFn = (
  columns: { id: string; key: string }[],
  exportFn: string,
  forms: any[],
  formValueList: any[]
) => {
  // 获取计算参数
  const defaultObj: {
    [key: string]: number | string | undefined
  } = {}
  for (let i = 0; i < columns.length; i++) {
    const formItem = forms.find((el) => el.config.key === columns[i].id)
    const formConfig = formItem.config
    const formValue = formValueList.find((el) => el.key === columns[i].id)
    const result = utils.getInputValue(formItem.formType, formValue, formConfig)
    defaultObj[columns[i].key] = result
  }
  if (exportFn) {
    const arr: string[] = columns
      .filter((el) => {
        return exportFn.indexOf(el.key) > -1
      })
      .map((el) => {
        return el.key
      })
    let exportVal = exportFn
    for (let i = 0; i < arr.length; i++) {
      const key = arr[i]
      const value = defaultObj[key]
      exportVal = exportVal.replace(key, value)
    }
    const fn = new Function(exportVal)
    return fn()
  } else {
    return ''
  }
}
